﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using Fsb.Utility;
using VideoCache.Security.Implements;

namespace VideoCache.Security
{
    public class SecurityResponseModel
    {
        /// <summary>
        /// 返回的http代码
        /// </summary>
        public HttpStatusCode StatusCode { get; set; }

        /// <summary>
        /// 返回的加密的字符串
        /// </summary>
        public string ResponseText { get; set; }

        /// <summary>
        /// 辅助加密hash
        /// </summary>
        public string Hash { get; set; }

        public SecurityResponseModel() { }

        public SecurityResponseModel(object obj)
        {
            this.StatusCode = HttpStatusCode.OK;

            string json = JsonUtility.Json(obj);

            // 使用json的值做md5 hash并将值存入Hash属性，用以确认值是否被串改

            this.Hash = new MD5Provider().Encrypt(json);

            this.ResponseText = this.Encrypt(json);
        }

        private string Encrypt(string json)
        {
            ISecurityProvider provider = new DesProvider();

            return provider.Encrypt(json);
        }

        private string Decrypt(string code)
        {
            ISecurityProvider provider = new DesProvider();

            return provider.Decrypt(code);
        }

        public bool IsValidate()
        {
            string json = this.Decrypt(this.ResponseText);

            string hash = new MD5Provider().Encrypt(json);

            return hash == this.Hash;
        }

        public T GetObject<T>()
        {
            string json = this.Decrypt(this.ResponseText);

            if (this.IsValidate())
            {
                return JsonUtility.Object<T>(json);
            }

            throw new Exception("无法解密。");
        }
    }
}